package com.whynot.frame.basic.util;

import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 
 * <ol>从BEAN数组中提取某一列的字符串数组，或者字符串拼接值
 * <li>{@link BeanUtils }</li>
 * <li>{@link StringUtils }</li>
 * </ol>
 * @see
 * @author wanghui 
 * @since 1.0
 * @2015年12月11日
 *
 */
public class BeanListUtils {

	/**
	 * 获取数组中某一列的值
	 * @param ls
	 * @param fieldName
	 * @return
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public static List<String> getFieldList(List<? extends Object> ls,
			String fieldName) throws  Exception {
		List<String> coList = new ArrayList<String>(ls.size());
		for (Object obj : ls) {
			coList.add(BeanUtils.getProperty(obj, fieldName) );
		}
		return coList;
	}
	
	/**
	 * 获得单列的字符串拼接值
	 * @param ls
	 * @param fieldName
	 * @param escapeNull 最终拼接的字符串是否剔除为空的对象
	 * @param nullToBlank 空对象是否转为空串
	 * @param joinStr
	 * @return
	 * @throws Exception
	 */
	public static String getJoinStr(List<? extends Object> ls,
			String fieldName,boolean escapeNull,boolean nullToBlank, String joinStr) throws  Exception {
		List<String> strLs = getFieldList(ls,fieldName);
		List<String> strLs1 = new ArrayList<String>();
		for (int i = 0; strLs != null && i < strLs.size(); i++) {
			String val = strLs.get(i);
			//为NULL不拼接到最终的字符中
			if (escapeNull && val==null) {
				continue;
			}
			if(nullToBlank)
				val = StringUtils.asString(val);
			strLs1.add(val);
		}
		return StringUtils.join(strLs1, joinStr);
	}
	
	/**
	 * 获得单列的字符串拼接值
	 * @param ls
	 * @param fieldName
	 * @return
	 * @throws Exception
	 */
	public static String getJoinStr(List<? extends Object> ls,
			String fieldName) throws  Exception {
		return getJoinStr(ls,fieldName,true,true,",");
	}
	
	@Test
	public void test() throws Exception{
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>> ();
		Map<String, Object> context = new HashMap<String, Object>();
		
		Map<String, Object> context2 = new HashMap<String, Object>();
		context2.put("key", "value2");
		
		Map<String, Object> context3 = new HashMap<String, Object>();
		context3.put("key", "value3");
		
		list.add(context2);
		list.add(context);
		list.add(context3);
		
		System.out.println(	BeanListUtils.getJoinStr(list,"key",false,true,","));
		System.out.println(	StringUtils.parseToSqlOr("1,3,3","code_id"));
	}

}
